package com.geeklan.smart.ui.feed.fragment;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.geeklan.base.base.BaseFragment;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.FeedRule;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.FragmentFeedingRuleBinding;
import com.geeklan.smart.ui.feed.EditFeedPlanActivity;
import com.geeklan.smart.ui.feed.FeedPlanActivity;
import com.geeklan.smart.ui.feed.fragment.adapter.FeedingRuleAdapter;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;
import com.geeklan.smart.widget.ItemOnClickListener;

import java.util.ArrayList;
import java.util.List;

public class FeedingRuleFragment extends BaseFragment<FragmentFeedingRuleBinding> implements ItemOnClickListener {
    private PetViewModel petViewModel;
    private ArrayList<FeedRule> timedPlans = new ArrayList<>();
    private FeedingRuleAdapter mAdapter;
    private String deviceId;
    private int updatePosition = 0;

    public FeedingRuleFragment() {

    }

    @Override
    protected FragmentFeedingRuleBinding initBinding() {
        return FragmentFeedingRuleBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        deviceId = getActivity().getIntent().getStringExtra("deviceId");
        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);

        petViewModel.getFeedRuleList().observe(this, response -> {
            timedPlans.clear();
            timedPlans.addAll(response);

            if(isAdded()){
                FeedPlanActivity feedPlanActivity = (FeedPlanActivity) getActivity();
                feedPlanActivity.setTimedPlans(timedPlans);
            }

            mAdapter.notifyDataSetChanged();
            mBinding.smartRefreshLayout.finishRefresh();

            if(timedPlans.isEmpty()){
                mBinding.llNotData.setVisibility(View.VISIBLE);
                mBinding.rvFeedRule.setVisibility(View.GONE);
            }else {
                mBinding.llNotData.setVisibility(View.GONE);
                mBinding.rvFeedRule.setVisibility(View.VISIBLE);
            }
        });

        petViewModel.getFeedRuleErrorList().observe(this, s -> {
            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
            mBinding.smartRefreshLayout.finishRefresh();

            if(isAdded()){
                FeedPlanActivity feedPlanActivity = (FeedPlanActivity) getActivity();
                feedPlanActivity.setTimedPlans(timedPlans);
            }
        });


        petViewModel.getDeleteFeedPlanLiveData().observe(this, response -> {
            dismiss();
            mBinding.smartRefreshLayout.autoRefresh();
        });

        petViewModel.getDeleteFeedPlanErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
        });

        petViewModel.getUpdateFeedPlanLiveData().observe(this, response -> {
            dismiss();
            Toast.makeText(mContext, R.string.update_success, Toast.LENGTH_SHORT).show();
//            mBinding.smartRefreshLayout.autoRefresh();
        });

        petViewModel.getUpdateFeedPlanErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onResume() {
        mBinding.smartRefreshLayout.autoRefresh();
        super.onResume();
    }

    @Override
    protected void initView() {
        mAdapter = new FeedingRuleAdapter(mContext, timedPlans);
        mAdapter.setItemOnClickListener(this);
        mAdapter.setDeleteItemListener(new FeedingRuleAdapter.DeleteItemListener() {
            @Override
            public void onDelete(FeedRule timedPlan, int position) {
                loading();
                petViewModel.deleteFeedRule(timedPlan.getId());
            }

            @Override
            public void isOpen(boolean isOpen,FeedRule timedPlan, int position) {
                updatePosition = position;
                timedPlan.setIsOpen(isOpen?1:0);
//                timedPlan.setEffectivTime("1");
                loading();
                petViewModel.updateFeedRule(timedPlan);
            }
        });
        mBinding.rvFeedRule.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.rvFeedRule.setAdapter(mAdapter);


        mBinding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            petViewModel.getFeedRuleList(deviceId);
        });


        activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        if (result.getData() != null) {
                            boolean isRefresh = result.getData().getBooleanExtra("isRefresh", false);
                            if (isRefresh) {
                                mBinding.smartRefreshLayout.autoRefresh();
                            }
                        }
                    }
                });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    private ActivityResultLauncher<Intent> activityResultLauncher;

    @Override
    public void OnItemClick(View view, int position) {
        Intent intent = EditFeedPlanActivity.startActivity(mContext, timedPlans.get(position),deviceId,timedPlans);
        activityResultLauncher.launch(intent);
    }
}
